<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <el-steps :space="200" :active="activename-0" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="AddGoodsFormData"
        :rules="AddGoodsFormRules"
        ref="AddGoodsFormRef"
        :label-position="'top'"
      >
        <el-tabs
          @tab-click="handleTabClick"
          :before-leave="handleTabsChange"
          v-model="activename"
          :tab-position="'left'"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="AddGoodsFormData.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="AddGoodsFormData.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="AddGoodsFormData.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="AddGoodsFormData.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="AddGoodsFormData.goods_cat"
                :options="AddGoodsCascaderData"
                :props="AddGoodsCascaderProps"
                @change="handleCascaderChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="(item) in manyParamsData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="item1"
                  v-for="(item1,index) in item.attr_vals"
                  :key="index"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="(item) in onlyParamsData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :headers="headers"
              :on-success="handlePicUpload"
              action="http://timemeetyou.com:8889/api/private/v1/upload"
              :on-preview="handlePicPreview"
              :on-remove="handlePicRemove"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="AddGoodsFormData.goods_introduce" />
            <el-button class="submit" type="primary" @click="AddGoods">确认添加</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="图片预览" :visible.sync="PreviewPicDialogVisible" width="50%">
      <img class="PreviewIMG" :src="PreviewPicURL" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activename: 0,
      AddGoodsFormData: {
        goods_name: "",
        goods_price: "",
        goods_weight: "",
        goods_number: "",
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: []
      },
      AddGoodsFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" }
        ]
      },
      AddGoodsCascaderData: [],
      AddGoodsCascaderProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children"
      },
      manyParamsData: [],
      onlyParamsData: [],
      headers: { Authorization: window.sessionStorage.getItem("token") },
      PreviewPicURL: "",
      PreviewPicDialogVisible: false
    };
  },
  created() {
    this.getAddCascaderData();
  },
  methods: {
    async getAddCascaderData() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) return this.$message.error("操作失败");
      this.AddGoodsCascaderData = res.data;
    },
    handleCascaderChange() {
      if (this.AddGoodsFormData.goods_cat.length !== 3) {
        this.AddGoodsFormData.goods_cat = [];
        return this.$message.error("只允许选择三级商品分类");
      }
    },
    //当没选择三级商品分类时阻止标签发生切换
    handleTabsChange(activename, oldname) {
      if (oldname === "0" && this.AddGoodsFormData.goods_cat.length !== 3) {
        this.$message.error("请选择商品分类");
        return false;
      }
    },
    async handleTabClick() {
      if (this.activename === "1") {
        const { data: res } = await this.$http.get(
          `categories/${this.CateID}/attributes`,
          {
            params: { sel: "many" }
          }
        );
        if (res.meta.status !== 200) return this.$message.error("操作失败");
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
        });

        this.manyParamsData = res.data;
      } else if (this.activename === "2") {
        const { data: res } = await this.$http.get(
          `categories/${this.CateID}/attributes`,
          {
            params: { sel: "only" }
          }
        );
        if (res.meta.status !== 200) return this.$message.error("操作失败");

        this.onlyParamsData = res.data;
        console.log(this.onlyParamsData);
      }
    },
    handlePicUpload(response) {
      const pic = { pic: response.data.tmp_path };
      this.AddGoodsFormData.pics.push(pic);
    },
    handlePicRemove(file) {
      const index = this.AddGoodsFormData.pics.findIndex(
        item => item.pic === file.response.data.tmp_path
      );
      this.AddGoodsFormData.pics.splice(index, 1);
    },
    handlePicPreview(file) {
      this.PreviewPicURL = file.response.data.url;
      this.PreviewPicDialogVisible = true;
    },
    AddGoods() {
      this.$refs.AddGoodsFormRef.validate(async value => {
        if (!value) return this.$message.error("请添加完整的商品信息");
        let form = JSON.parse(JSON.stringify(this.AddGoodsFormData));
        form.goods_cat = form.goods_cat.join(",");
        this.manyParamsData.forEach(item => {
          const attr = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(",")
          };
          form.attrs.push(attr);
        }),
          this.onlyParamsData.forEach(item => {
            const attr = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            };
            form.attrs.push(attr);
          });
        const { data: res } = await this.$http.post("goods", form);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success("添加成功");
        this.$router.push("/goods");
      });
    }
  },
  computed: {
    CateID() {
      if (this.AddGoodsFormData.goods_cat.length === 3) {
        return this.AddGoodsFormData.goods_cat[2];
      } else {
        return null;
      }
    }
  }
};
</script>

<style lang="less" scoped>
.el-steps {
  margin: 15px 0;
}
.PreviewIMG {
  width: 100%;
}
.submit {
  margin-top: 15px;
}
</style>